﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DunSilverlight.ViewModel;
using DunSilverlight.Comm;
using Telerik.Windows.Controls;

namespace DunSilverlight.Views
{
    public partial class RightBindForm : UserControl
    {
        RightService.RightServiceClient ser = new RightService.RightServiceClient();
        RoleService.RoleServiceClient roleSer = new RoleService.RoleServiceClient();
        IList<RightModel> roleRight;
        int roleId;
        public RightBindForm(int roleId, IList<RightModel> roleRight)
        {
            InitializeComponent();
            roleSer.AddRightsCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(roleSer_AddRightsCompleted);
            ser.GetListByHQLCompleted += new EventHandler<RightService.GetListByHQLCompletedEventArgs>(ser_GetListByHQLCompleted);
            ser.GetListByHQLAsync("From Right");

            this.roleId = roleId;
            this.roleRight = roleRight;
        }

       

        void ser_GetListByHQLCompleted(object sender, RightService.GetListByHQLCompletedEventArgs e)
        {
            int totalCount;
            var entityList = JsonSerializerHelper.JsonToEntities<DunLibrary.User.Right>(e.Result, out totalCount);

            IList<RightModel> modelList = new List<RightModel>();
            foreach (var item in entityList)
            {
                modelList.Add(RightModel.Create(item));
            }

            var idlist = roleRight.Select(c=>c.Id);
            modelList.Where(c => idlist.Contains(c.Id)).ToList().ForEach(c => c.IsInRole = true);
            
            ListRight.ItemsSource = modelList;

        }
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            List<RightModel> modelList = ListRight.ItemsSource as List<RightModel>;
            var list = modelList.Where(c => c.IsInRole == true).Select(c => c.Id);
            string ids = string.Join(",", list);
            roleSer.AddRightsAsync(roleId, ids);
        }

        void roleSer_AddRightsCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            (this.Parent as RadWindow).Close();
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            (this.Parent as RadWindow).Close();
        }
    }
}
